using UnityEngine;
using System.Collections;

public class Follower : MonoBehaviour
{
	[SerializeField]
	private Transform minLimit = null, maxLimit = null;
	
	[SerializeField]
	private Transform objectToFollow;
	
	[SerializeField]
	private Vector3 offset;
	
	[SerializeField]
	private bool followOnAwake = true;
	
	private bool tweenUpdating = true;
	
	void Awake()
	{
		tweenUpdating = followOnAwake;
	}
	
	void Update()
	{
		//Debug.DrawLine(transform.position - (Vector3.up * camera.orthographicSize), (transform.position - (Vector3.right * (Screen.width/(Screen.height * 1.0f)))) + Vector3.up * 2000, Color.red);
		if(objectToFollow)
		{
			Vector3 newPos = objectToFollow.position + offset;
			
			if(minLimit)
			{
				if(newPos.x < minLimit.position.x + camera.orthographicSize * (Screen.width/(Screen.height * 1.0f)))
				{newPos = new Vector3(minLimit.position.x + camera.orthographicSize * (Screen.width/(Screen.height * 1.0f)), newPos.y, -2);}
				if(newPos.y < minLimit.position.y + camera.orthographicSize)
				{newPos = new Vector3(newPos.x, minLimit.position.y + camera.orthographicSize, -2);}
			}
			
			if(maxLimit)
			{
				if(newPos.x > maxLimit.position.x - camera.orthographicSize * (Screen.width/(Screen.height * 1.0f)))
				{newPos = new Vector3(maxLimit.position.x - camera.orthographicSize * (Screen.width/(Screen.height * 1.0f)), newPos.y, -2);}
				if(newPos.y > maxLimit.position.y - camera.orthographicSize)
				{newPos = new Vector3(newPos.x, maxLimit.position.y - camera.orthographicSize, -2);}
			}
			
			if(tweenUpdating)
			{
				transform.position = iTween.Vector3Update(transform.position, newPos, 15);
				float dist = Vector2.Distance(new Vector2(transform.position.x, transform.position.y), new Vector2(newPos.x, newPos.y));
				
				if(dist < 5f)
				{
					tweenUpdating = false;
				}
			}
			else
			{
				transform.position = newPos;
			}
		}
	}
	
	public void NewTarget(Transform target, Vector3 newOffset)
	{
		if(!target.Equals(objectToFollow))
		{
			tweenUpdating = true;
			objectToFollow = target;
		}
		
		if(!newOffset.Equals(offset))
		{
			tweenUpdating = true;
			offset = newOffset;
		}
	}
	
	public void NewOffset(Vector3 newOffset)
	{
		if(!newOffset.Equals(offset))
		{
			tweenUpdating = true;
			offset = newOffset;
		}
	}
	
	public void NewMaxMin(Transform min, Transform max)
	{
		if(this.minLimit != min)
		{
			this.minLimit = min; 
			tweenUpdating = true;
		}
		
		if(this.maxLimit != max)
		{
			this.maxLimit = max;
			tweenUpdating = true;
		}
	}
	
	public bool FinishTween
	{
		get { return !tweenUpdating; }
	}
}
